<template>
  <van-button
    round
    size="small"
    v-if="is_followed"
    @click="onFollow"
    :loading="loading"
    >已关注</van-button
  >
  <van-button
    v-else
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="loading"
    @click="onFollow"
    >关注</van-button
  >
</template>
<script>
import { addFollow, deleteFollow } from "@/api/user";
export default {
  name: "followUser",

  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      loading: false
    };
  },
  methods: {
    async onFollow() {
      // 判断当前是否登录
      if (!this.$store.state.user) {
        this.$toast("请先登录");
        return this.$router.push("/login?redirect=" + this.$route.path);
      }

      this.loading = true;
      try {
        // 判断当前是什么状态
        if (this.is_followed) {
          // 进行取消关注
          await deleteFollow(this.userId);
          this.$toast.success("取消成功");
        } else {
          // 进行添加关注
          await addFollow(this.userId);
          this.$toast.success("关注成功");
        }
        this.$emit("update:is_followed", !this.is_followed);
      } catch (error) {
        this.$toast.fail("操作失败");
      }
      this.loading = false;
    }
  }
};
</script>
<style lang="less" scoped></style>
